package dao

import (
	"errors"
	"fmt"
	"goadmin/conf"
	"goadmin/model"
	"goadmin/utils"

	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

type Condition func(db *gorm.DB) *gorm.DB

var db *gorm.DB

func init() {
	dsn := fmt.Sprintf("host=%s port=%d dbname=%s user=%s password=%s sslmode=disable TimeZone=Asia/Shanghai",
		conf.Database.Host, conf.Database.Port, conf.Database.Db, conf.Database.User, conf.Database.Pwd)
	var err error
	if db, err = gorm.Open(
		postgres.New(postgres.Config{
			DSN: dsn,
		}),
		&gorm.Config{
			SkipDefaultTransaction: true, // 禁用默认事务
			NamingStrategy: schema.NamingStrategy{
				SingularTable: true, // 表名不加s
			},
		}); err != nil {
		panic(err)
	}
	db.AutoMigrate(&model.User{}, &model.File{})
	if err := db.Where(&model.User{Username: conf.User.Super}).First(&model.User{}).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			if err := db.Create(&model.User{Username: conf.User.Super, Password: conf.User.DefaultPwd, Auth: utils.AuthSuper}).Error; err != nil {
				panic(err)
			}
		}
	}

	if conf.App.Mode == "debug" {
		db = db.Debug()
	}
}

// 分页
func paginate(page int, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page < 1 {
			page = 1
		}
		if pageSize < 1 {
			pageSize = 10
		}
		return db.Offset((page - 1) * pageSize).Limit(pageSize)
	}
}
